package org.jeecg.modules.extbpm.listener.task;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.extbpm.process.common.WorkFlowGlobals;
import org.jeecg.modules.extbpm.process.entity.ExtActDesignFlowData;
import org.jeecg.modules.extbpm.process.mapper.ExtActDesignFlowDataMapper;
import org.jeecg.modules.extbpm.process.pojo.DesignFormDataDTO;
import org.jeecg.modules.extbpm.process.service.IExtActProcessService;
import org.jeecg.modules.extbpm.util.JSONHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * @author scott
 * 通过节点监听更新业务数据在流程里面的变量数据
 */
@Slf4j
public class TaskUpdateFormDataListener implements TaskListener {
    private static final long serialVersionUID = 1L;
    private static IExtActProcessService extActProcessService;
    private static ExtActDesignFlowDataMapper extActDesignFlowDataMapper;

    static {
        extActProcessService = SpringContextUtils.getBean(IExtActProcessService.class);
        extActDesignFlowDataMapper = SpringContextUtils.getBean(ExtActDesignFlowDataMapper.class);
    }

    @Override
    public void notify(DelegateTask delegateTask) {
        //获取主流程实例
        String processInstanceId = delegateTask.getProcessInstanceId();
        DelegateExecution execution = delegateTask.getExecution();
        String bpmDataId = (String) execution.getVariable(WorkFlowGlobals.BPM_DATA_ID);
        String businessKey = (String) execution.getVariable(WorkFlowGlobals.BPM_FORM_KEY);

        Map<String, Object> dataForm = new HashMap<String, Object>();
        if(WorkFlowGlobals.DESIGN_FORM_DRAFT_TABLE.equals(businessKey)){
            //如果是表单设计器的数据（需要关联通过中间表取数据）
            ExtActDesignFlowData extActDesignFlowData = extActDesignFlowDataMapper.selectById(bpmDataId);
            DesignFormDataDTO designFormDataDTO = extActDesignFlowDataMapper.getDesignFormDataById(extActDesignFlowData.getDesformDataId());
            dataForm = JSONHelper.json2MapNoObj(designFormDataDTO.getDesformDataJson());
        }else{
            //获取对应的物理表的业务数据
            dataForm = extActProcessService.getDataById(businessKey, bpmDataId);
        }
        if (dataForm != null && !dataForm.isEmpty()) {
            for (Map.Entry<String, Object> entry : dataForm.entrySet()) {
                String mapKey = entry.getKey();
                Object mapValue = entry.getValue();
                log.info(" 同步更变流程变量 execution.setVariable => "+ mapKey + ":" + mapValue);
                execution.setVariable(mapKey, mapValue);
            }
        }
    }

}
